<?php

namespace API\App\Action;

use Hx\App;
use Hx\Event;
use Hx\Request;

class Blog {

    public function __construct() {
        Event::trigger('token-validate');
    }

    public function getList() {
        $page = Request::get('page');
        $page = $page > 1 ? $page : 1;
        $data = App::Model('Blog->getList', array('1=1', $page, 8));
        return !$data ? array('error' => true, 'msg' => '查询失败') : $data;
    }

    public function getOne($id) {
        $data = App::Model('Blog->getOne', array((int)$id));
        return !$data ? array('error' => true, 'msg' => '查询失败') : array('blog' => $data);
    }

    public function getArchive() {
        $data = App::Model('Blog->getArchive');
        return !$data ? array('error' => true, 'msg' => '查询失败') : array('blog' => $data);
    }

    public function getPrivates() {
        $page = Request::get('page');
        $page = $page > 1 ? $page : 1;
        $data = App::Model('Blog->getList', array('N.status != "public"', $page, 8, false));
        return !$data ? array('error' => true, 'msg' => '查询失败') : $data;
    }

    public function addBlog() {
        $data = Request::post(true);
        if (!$data['title'] || !$data['nodeKey'] || !$data['content']) {
            return array('error' => true, 'msg' => '参数不全');
        }
        $data['userId'] = (int)Request::getHttp('X_User');
        $data = App::Model('Blog->addBlog', array($data));
        return $data === false ? array('error' => true, 'msg' => '添加失败') : array('blog' => $data);
    }

    public function changeStatus() {
        $status = Request::post('status');
        if (!$status) {
            $status = 'draft';
        }
        $id = (int)Request::post('id');
        $res = App::Model('Blog->changeStatus', array($id, $status));
        Event::trigger('category-count');
        return $res === false ? array('error' => true, 'msg' => '更新失败') : array('result' => true);
    }
}